﻿using Autofac;
using DesignByContract;
using FluentNHibernate;
using MadMediaManager.Core.DependencyInjectionSupport;
using MadMediaManager.Core.Interfaces.DataAccess;
using MadMediaManager.Core.Interfaces.DependencyInjectionSupport;
using MadMediaManager.Core.Interfaces.Services;
using MadMediaManager.DataAccess.Database;
using MadMediaManager.DataAccess;

namespace MadMediaManager.Infrastructure
{
    public class ContainerConfigurator : IContainerConfigurator<IContainer>
    {
        private ContainerBuilder _containerBuilder;

        public ContainerConfigurator(IApplicationSettings appSettings)
        {
            Check.Require(appSettings != null, "appSettings cannot be null.");
            _containerBuilder = new ContainerBuilder();

            var nhibernateConfigProperties = new NHiberanteConfigurationPropertiesFactory(DatabaseType.SqlCe40,
                                                                                          appSettings.ConnectionString,
                                                                                          false);
            _containerBuilder.RegisterInstance(SessionSourceBuilder.Build(nhibernateConfigProperties.Properties,
                                                                 "MadMediaManager.DataAccess.dll")).As<ISessionSource>()
                                                                 .SingleInstance();

            _containerBuilder.Register(c => new NHibernateDbContext(c.Resolve<ISessionSource>().CreateSession()))
                .As<IDbContext>();
            /*
            _containerBuilder.Register(c => ViewModelUIService.CreateInstance()).As<IViewModelUIService>().
                SingleInstance();

            _containerBuilder.Register(c => new EventPublisher()).As<IEventPublisher>()
                .SingleInstance();

            _containerBuilder.Register(c => new MainWindowViewModel(c.Resolve<IViewModelUIService>()));

            _containerBuilder.Register(c => new HomeViewModel(c.Resolve<IDbContext>(), c.Resolve<IEventPublisher>()));*/
        }

        public IContainer Build()
        {
            var container = _containerBuilder.Build();
            _containerBuilder = null;
            return container;
        }
    }
}
